<?php

/**
 * Main configuration for the apAuthLocalUserPlugin
 *
 * @package    authpuppy
 * @subpackage plugin
 * @author     Geneviève Bastien <gbastien@versatic.net>
 * @version    Bzr: $Id: pre-alpha$
 */

class apExternalCMSMain  {
  
  protected static $_plugin; 
  
  /**
   * Returns the plugin object associated with this plugin
   * @return apPlugin
   */
  public static function getPlugin() {
    if (is_null(self::$_plugin))
      self::$_plugin = apPlugin::getPlugin('apExternalCMSPlugin');
    return self::$_plugin;
  }
  
  /**
   * Function called by the loginpage.request event.  It is called by a notifyUntil event
   * ** This feature should eventually look more like the portal page, but changes need to be made to the core **
   * @param sfEvent $event
   * @return boolean whether the event was processed or not
   */
  public static function forwardLogin(sfEvent $event) {
    $node = $event['node'];
    
    if ($node) {
      if (!is_null($node->getLoginPage()) && ($node->getLoginPage() != '')) {
        $loginpage = $node->getLoginPage();
        $loginpage = self::replacePlaceHolders($loginpage, $node);
        $event->getSubject()->redirect($loginpage);
      }
      elseif (self::getPlugin()->getConfigValue('redirect_login_page', false)) {
	    $externalurl = self::getPlugin()->getConfigValue('external_url', '');
	    $loginpage = self::getPlugin()->getConfigValue('login_page', '');
	      
	    $loginpage = self::replacePlaceHolders($loginpage, $node);
	      
		// forward to the login page
	    $event->getSubject()->redirect($externalurl . $loginpage);
	    return true;
      }
    }
    else
      return false;
  }
 
  /**
   * Function called by the portalpage.request event.  It is a filter event.  If the portal
   *   page needs to be redirected, it returns in the $result['redirect'] the url of the page
   *   to redirect to.
   * @param $event
   * @param $result
   */
  public static function forwardPortal(sfEvent $event, $result) {
    $node = $event['node'];

    if ($node && (self::getPlugin()->getConfigValue('redirect_portal_page', false))) {
      
      if (!is_null($node->getPortalPage()) && ($node->getPortalPage() != '')) {
        $event->getSubject()->redirect($node->getPortalPage());
      } else {
        $externalurl = self::getPlugin()->getConfigValue('external_url', '');
        $portalpage = self::getPlugin()->getConfigValue('portal_page', '');
      
        $portalpage = self::replacePlaceHolders($portalpage, $node);
	  
	    // forward to the portal page
       // $event->getSubject()->redirect($externalurl . $portalpage);
        $result['redirect'] = $externalurl. $portalpage;

      }
    }
    return $result;
  }
  
  static public function replacePlaceHolders($url, $node) {
    // find placeholders and replace them
    // placeholders are of the form %something%
    preg_match_all("/\%(.*)\%/sU", $url, $matches, PREG_SET_ORDER);

    // $match[0] contains the full regex including '%'
	// $match[1] contains the string inside % %
	foreach ($matches as $match) {
	  $value = '';
	  switch($match[1]) {
	    case "nodename": $value = self::slugify($node->getName());
	      break;
	    case "gwid": $value = self::slugify($node->getGwId());
	      break;
	    case "nodeid": $value = self::slugify($node->getId());
	      break;
	    case "friendlyname": $value = $node->getFriendlyname();
	      break;
	    case "originurl": $value = sfContext::getInstance()->getUser()->getAttribute('url', '');
	      break;
	    case "identitytype": $identity = sfContext::getInstance()->getUser()->getAttribute('identity');
	      if (!is_null($identity)) {
	        $value = $identity->getAuthenticatorType();
	      }
	      break;
	    case "identityname": 
	      $identity = sfContext::getInstance()->getUser()->getAttribute('identity');
	      if (!is_null($identity)) {
	        $value = $identity->getId();
	      }
	      break;
	    case "getparameters":
	      $getParams = sfContext::getInstance()->getRequest()->getGetParameters();
	      $values = array();
	      foreach ($getParams as $name => $val) {
	        $values[] = $name . "=" . $val; 
	      }
	      $value = implode('&', $values);
	      break;
	    default: $value = '';
	  }
	  $url = str_replace($match[0], $value, $url);
	}
	return $url;
  }

  static public function slugify($text)
  {
    // replace all non letters or digits by -
    $text = preg_replace('/\W+/', '-', $text);
 
    // trim and lowercase
    $text = strtolower(trim($text, '-'));
 
    return $text;
  }
  
  public static function savingNode(sfEvent $event, $node) {
    return $node; 
  }
  
  public static function settingUpNode(sfEvent $event, $node) {
    $node->hasColumn('friendlyname', 'string', 50, array(
             'length' => 50,
        ));
    $node->hasColumn('portal_page', 'string', 500, array(
             'length' => 500,
        ));
     $node->hasColumn('login_page', 'string', 500, array(
             'length' => 500,
        ));
    return $node; 
  }
  
  /**
   * This function adds the geocoding form elements to the node form
   * @param sfEvent $event
   * @param sfForm $form
   */
  public static function changingForm(sfEvent $event, $form) {
    // Merge the extra node field form into the node form
    $nodefieldform = new apNodeFieldForm($form->getObject());
    $form->mergeForm($nodefieldform);

    return $form;
  }
  

}
